package com.quanyan.ic.common.http.exception;

import com.quanyan.ic.common.http.APIResponse;
import com.quanyan.ic.common.http.enums.ApiResponseEnum;
import com.quanyan.ic.common.http.enums.BizExceptionEnum;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * Controller层，全局异常捕获，处理从业务层抛出的BizException, 封装成APIResponse返回
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = {BizException.class, RuntimeException.class})
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    @SuppressWarnings("unchecked")
    public ResponseEntity<?> bizExceptionHandler(RuntimeException e) {
        if (e instanceof BizException) {
            logger.warn("bizExceptionHandler: stacktrace={}", ExceptionUtils.getStackTrace(e));
            BizException bizException = (BizException) e;
            if (bizException.getBaseEnum() == null) {
                BizExceptionEnum bizExceptionEnum = new BizExceptionEnum("FAIL", bizException.getMessage());
                return new ResponseEntity(
                        APIResponse.returnFail(bizException.getErrorData(), bizExceptionEnum), HttpStatus.OK);
            } else {
                return new ResponseEntity(
                        APIResponse.returnFail(bizException.getErrorData(), bizException.getBaseEnum()), HttpStatus.OK);
            }
        }
        logger.error("bizExceptionHandler: stacktrace={}", ExceptionUtils.getStackTrace(e));
        return new ResponseEntity(
                APIResponse.returnFail(HttpStatus.BAD_REQUEST.value(), e.getCause() == null ? "null" : e.getCause().getMessage()), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    @SuppressWarnings("unchecked")
    public ResponseEntity<?> internalExceptionHandler(Exception e) {
        logger.error("internalExceptionHandler: stacktrace={}", ExceptionUtils.getStackTrace(e));
        return new ResponseEntity(APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
